# -*- coding: windows-1251 -*-

from django import template

register = template.Library()

@register.simple_tag
def myauth_vk_header( domain, app_id, window_title ):
	return """
		<script type='text/javascript'>
	function loginVk()
	{
		window.open(	"http://oauth.vk.com/authorize?client_id={{app_id}}&redirect_uri=http://{{domain}}/auth/vk&response_type=code&display=popup", 
						"{{window_title}}",
						"width=400,height=400"
						 ); 
	}
</script>""".format( domain = domain, app_id = app_id, window_title = window_title )


def myauth_fb_header( domain, app_id ):
	"""
		<div id="fb-root"></div>
		<script>
		  // Additional JS functions here
			window.fbAsyncInit = function() 
			{
				FB.init(	{
								appId      : '{{app_id}}', // App ID
								channelUrl : '//{{domain}}/fb_channel.html', // Channel File
								status     : true, // check login status
								cookie     : true, // enable cookies to allow the server to access the session
								xfbml      : true  // parse XFBML
							}
				);
		
				if (typeof facebookInit == 'function') {
					FB.getLoginStatus(	function(response)
										{
											if (response.status === 'connected') 
											{
												// connected
												//response.accessToken
												//response.userId
											} 
											else  
											{
												loginFb();
											}
										}
					);
				}           
		
			// Additional init code here
		
			};
		
		  // Load the SDK Asynchronously
		  (function(d){
		     var js, id = 'facebook-jssdk', ref = d.getElementsByTagName('script')[0];
		     if (d.getElementById(id)) {return;}
		     js = d.createElement('script'); js.id = id; js.async = true;
		     js.src = "//connect.facebook.net/en_US/all.js";
		     ref.parentNode.insertBefore(js, ref);
		   }(document));
		
			function loginFb() 
			{
				FB.login(	function( response ) 
							{
								if( response.authResponse ) 
								{
									FB.api('/me',	function(response) 
													{
														$.ajax(	{
																	'url': "/auth/fb/",
																	'type': "POST",
																	'dataType': "json",
																	'data': response,
																	'success': fbSuccess
																} );	
													}
									);
								} 
								else 
								{
									// cancelled
								}
							}
				);
			}

			function fbSuccess( data )
			{
				document.location.href = data[ 'link' ];
			}
		</script>
	
		""".format( domain = domain, app_id = app_id )

